package com.abc.robot01.fragment

import android.app.Activity
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.fragment.app.viewModels
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import com.abc.robot01.R
import com.abc.robot01.activity.BaseActivity
import com.abc.robot01.activity.MyFont_Size
import com.abc.robot01.activity.MySlider
import com.abc.robot01.activity.px
import com.abc.robot01.vivemodel.VideoFragmentViewModel
import com.abc.robot01.vivemodel.WalletViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


/**
 * A simple [Fragment] subclass as the default destination in the navigation.
 */
class VideoFragment(private val fileUrl: String, private val index: Int) : Fragment() {

    val TAG = "VideoFragment"

    private val viewModel: VideoFragmentViewModel by viewModels()

    private lateinit var player: ExoPlayer
    private var job: Job? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e(TAG, "onCreate");
        player =
            ExoPlayer.Builder(this.requireContext()).build()
    }

    override fun onPause() {
        Log.e(TAG, "onPause");
        super.onPause()
        player.pause()
        job?.cancel()
        job=null;
    }

    override fun onResume() {
        super.onResume()
        player.play()
        Log.e(TAG, "onResume");
    }

    override fun onStart() {
        super.onStart()
        Log.e(TAG, "onStart");
    }

    override fun onStop() {
        super.onStop()
        Log.e(TAG, "onStop");
    }

    override fun onDestroy() {
        super.onDestroy()
        player.stop()
        player.release();
        Log.e(TAG, "onDestroy");
    }

    override fun onDetach() {
        super.onDetach()
        Log.e(TAG, "onDetach");
    }

    override fun onAttach(activity: Activity) {
        super.onAttach(activity)
        Log.e(TAG, "onAttach activity");
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        Log.e(TAG, "onAttach Context");
    }

    private fun playPrevious() {
        (requireActivity() as BaseActivity).playPrevious(index)
    }

    private fun playNext() {
        // 调用所在的 Activity 的方法
        (requireActivity() as BaseActivity).playNext(index)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return ComposeView(requireContext()).apply {
            setContent {
                VideoPlayerScreen(player,
                    onPlayPrevious = ::playPrevious,
                    onPlayNext = ::playNext,
                    onPause = { player.pause() }
                )
            }
        }
    }

    fun formatDuration(durationMillis: Long): String {
        val minutes = (durationMillis / 1000 / 60).toInt()
        val seconds = (durationMillis / 1000 % 60).toInt()
        return String.format("%02d:%02d", minutes, seconds)
    }

    @Composable
    fun VideoPlayerScreen(
        exoPlayer: ExoPlayer,
        onPlayPrevious: () -> Unit,
        onPlayNext: () -> Unit,
        onPause: () -> Unit
    ) {
        val videoDuration = remember { mutableStateOf(10000000000L) }
        val scope = rememberCoroutineScope()
        var sliderPosition by remember { mutableStateOf(0L) }
        Box(modifier = Modifier.fillMaxSize()) {
            AndroidView(
                factory = { context ->
                    PlayerView(context).apply {
                        this.setOnTouchListener { _, _ -> false }
                        player = exoPlayer
                        this.useController = false
//                        val fileUrl = "file:///sdcard/The_Fisherman.mp4"
                        (player as ExoPlayer).setMediaItem(MediaItem.fromUri(Uri.parse(fileUrl)))
                        (player as ExoPlayer).prepare()
                        (player as ExoPlayer).repeatMode = Player.REPEAT_MODE_ONE
                        (player as ExoPlayer).playWhenReady = true
                        exoPlayer.addListener(object : Player.Listener {
                            override fun onIsPlayingChanged(isPlaying: Boolean) {
//                                Log.e(TAG,"exoPlayer.duration"+   videoDuration.value)
                            }

                            override fun onPlaybackStateChanged(state: Int) {
                                if (state == Player.STATE_READY) {
                                    videoDuration.value = exoPlayer.duration
                                }
                            }
                        })

                   job = scope.launch {
                            while (true) {
                                delay(1000);
                                if(viewModel.playing.value){
                                sliderPosition = exoPlayer.currentPosition
                                }
                            Log.e("PlayerFragment","sliderPosition $sliderPosition")
                            }
                        }
                    }
                },
                modifier = Modifier
                    .fillMaxSize()
                    .clickable(
                        indication = null,  // Removes the ripple effect
                        interactionSource = remember { MutableInteractionSource() })
                    {
                        viewModel.fullScreen.value = false
                        (requireActivity() as BaseActivity).fullScreen(false)
                    }
            )

            val fullScreen by remember {
                viewModel.fullScreen
            }

            if (fullScreen.not()) {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color.Transparent),
                    verticalArrangement = Arrangement.Bottom,
//                    horizontalAlignment = Alignment.CenterHorizontally
                )
                {

//            Text(text = formatDuration(videoDuration.value),
//                modifier = Modifier.background(Color.Transparent),
//                    color= Color.White
//            )

                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.padding(start = 30.px, end = 30.px).background(Color.Transparent)
                    ) {
                        Text(
                            fontSize = MyFont_Size, text = formatDuration(sliderPosition),
                            modifier = Modifier.background(Color.Transparent),
                            color = Color.White
                        )
                        Spacer(modifier = Modifier.width(20.px))
                        MySlider(
                            modifier = Modifier.weight(1.0f),
                            value = sliderPosition / (videoDuration.value * 1.0f),
                            onValueChange = { value ->
                                Log.e("PlayerFragment", "Slider onValueChange:  $value")
                                sliderPosition = (value * videoDuration.value).toLong()
                                exoPlayer.seekTo(sliderPosition);
                            },
                        )
                        Spacer(modifier = Modifier.width(20.px))
                        Text(
                            fontSize = MyFont_Size,
                            text = if (videoDuration.value == 10000000000L) "00:00" else formatDuration(
                                videoDuration.value
                            ),
                            modifier = Modifier.background(Color.Transparent),
                            color = Color.White
                        )
                    }
                    Spacer(modifier = Modifier.height(22.px))
                    Row(
                        modifier = Modifier
                            .background(Color.Transparent)
                            .padding(0.dp),
                    ) {
                        val isClicked = remember { mutableStateOf(false) }
                        val playing = remember {  viewModel.playing }
                        val imageResource = if (isClicked.value) {
                            R.drawable.left // 按下时显示的图片
                        } else {
                            R.drawable.left // 正常时显示的图片
                        }

                        val imageResource1 = if (playing.value) {
                            R.drawable.pause // 按下时显示的图片
                        } else {
                            R.drawable.play // 正常时显示的图片
                        }

                        val imageResource2 = if (isClicked.value) {
                            R.drawable.next // 按下时显示的图片
                        } else {
                            R.drawable.next // 正常时显示的图片
                        }

                        val full =
                            R.drawable.full // 按下时显示的图片

                        Spacer(modifier = Modifier.width(770.px))
                        // 创建 Image 组件，设置点击事件来切换状态
                        Image(
                            painter = painterResource(id = imageResource),
                            contentDescription = null,
                            modifier = Modifier
                                .size(60.px) // 设置图片大小
                                .clickable {
                                    isClicked.value = !isClicked.value
                                    onPlayPrevious()
                                } // 点击切换状态
                        )

                        Spacer(modifier = Modifier.width(100.px))

                        // 创建 Image 组件，设置点击事件来切换状态
                        Image(
                            painter = painterResource(id = imageResource1),
                            contentDescription = null,
                            modifier = Modifier
                                .size(60.px) // 设置图片大小
                                .clickable {
                                    playing.value = playing.value.not()
                                    if (playing.value) {
                                        exoPlayer.play()
                                    } else {
                                        exoPlayer.pause()
                                    }
                                } // 点击切换状态
                        )
                        Spacer(modifier = Modifier.width(100.px))

                        // 创建 Image 组件，设置点击事件来切换状态
                        Image(
                            painter = painterResource(id = imageResource2),
                            contentDescription = null,
                            modifier = Modifier
                                .size(60.px) // 设置图片大小
                                .clickable {
                                    isClicked.value = !isClicked.value
                                    onPlayNext()
                                } // 点击切换状态
                        )
                        Spacer(modifier = Modifier.width(200.px))
                        // 创建 Image 组件，设置点击事件来切换状态
                        Image(
                            painter = painterResource(id = full),
                            contentDescription = null,
                            modifier = Modifier
                                .size(60.px) // 设置图片大小
                                .clickable {
                                    viewModel.fullScreen.value = true
                                    (requireActivity() as BaseActivity).fullScreen(true)
                                } // 点击切换状态
                        )
                    }
                    Spacer(modifier = Modifier.height(32.px))
                }
            }
        }
    }
}